﻿using Microsoft.AspNetCore.Mvc;
using PMS.Core.Configuration.CommonEnumConfigs;
using PMS.Data.Entities.Settings;
using PMS.Services.EntityServices.SystemModules;
using PMS.Services.Utils.Security;
using PMS.Web.Framework.Components;
using System;
using System.Collections.Generic;
using System.Linq;

namespace PMS.Web.Components
{
    /// <summary>
    /// 系统模块操作按钮展示组件
    /// 按展示位置不同显示方式不同
    /// </summary>
    public class ModuleButtonTempletViewComponent : PMSViewComponent
    {

        private readonly AdminAreaSettings _adminAreaSettings;
        private readonly IPermissionService _permissionService;
        private readonly ISystemModuleService _systemModuleService;

        public ModuleButtonTempletViewComponent(AdminAreaSettings adminAreaSettings,
            IPermissionService permissionService,
            ISystemModuleService systemModuleService)
        {
            _adminAreaSettings = adminAreaSettings;
            _permissionService = permissionService;
            _systemModuleService = systemModuleService;
        }

        public IViewComponentResult Invoke(int moduleId, ModuleButtonGroup position)
        {
            var moduleEntity = _systemModuleService.GetSystemModuleById(moduleId);
            if (!moduleEntity.IsActive)
                return Content("");

            try
            {
                ViewBag.ModuleId = moduleEntity.Id;
                ViewBag.ButtonDisabled = _adminAreaSettings.DisableUnauthorizedButtons;
                var moduleAssignedBtns = _systemModuleService.GetModuleAssignedButtonsByIds(moduleId, moduleEntity.ModuleButtonIds.ToArray());
                var positionBtns = moduleAssignedBtns.Where(b => b.GroupType == position).ToList();
                if(positionBtns?.Any() ?? false)
                {
                    ViewBag.ModuleAssignedBtns = positionBtns;
                    var moduleAssingedBtnIdsAuth = new List<(int btnId, bool canAccess)>();
                    positionBtns.ForEach(b =>
                    {
                        if (_permissionService.AdminModuleButtonAuthorize(moduleEntity.Id, b.Id))
                            moduleAssingedBtnIdsAuth.Add((b.Id, true));
                        else moduleAssingedBtnIdsAuth.Add((b.Id, false));
                    });
                    ViewBag.ModuleAssignedBtnIdsWithAccess = moduleAssingedBtnIdsAuth;
                    return View(position);
                }
                return Content("");
                
            }
            catch(Exception ex)
            {
                if(ex is ArgumentNullException)
                    return Content("");
                throw ex;
            }
        }
    }
}
